<template xmlns:v-bind="http://www.w3.org/1999/xhtml">
  <div class="app-container-tree">
    <div class="dev-type-main-left">
      <!--鼠标右键菜单栏 -->
      <div v-show="showRightMenu">
        <div id="menu" class="rights-menu">

          <div v-if="clickedType.type==='Theme'" class="menu-item" @click="addHandle"><i class="iconfont" style="margin-right: 20px;height: 20px;">&#xe6a2;</i>添加</div>
          <div v-if="clickedType.label!=='未分类'|| clickedType.type==='Category'" class="menu-item" @click="editHandle"><i class="iconfont" style="margin-right: 20px;height: 20px;">&#xe635;</i>编辑</div>
          <div v-if="clickedType.label!=='未分类'|| clickedType.type==='Category'" class="menu-item" @click="deleteHandle"><i class="iconfont" style="margin-right: 20px;height: 20px;">&#xe61c;</i>删除</div>
        </div>
      </div>
      <div class="title-boxs">
        <input v-model="newCategoryDate" type="text" class="title" placeholder="添加一个新的分类">
        <el-button id="btn" type="primary" @click="addNewCategoryOnly"><i class="el-icon-edit" /> </el-button>
      </div>
      <el-tree
        ref="myTree"
        draggable
        :data="theme"
        :props="defaultProps"
        :filter-node-method="filterNode"
        class="filter-tree"
        :allow-drag="allDrag"
        :allow-drop="allDrop"
        @node-click="nodeClick"
        @node-contextmenu="rightClick"
        @node-drag-enter="dragEnter"
        @node-drag-leave="dragLeave"
        @node-drop="handleDrop"
      >
        <div slot-scope="{ node,data }">
          <span>
            <i v-if="data.children" class="iconfont" style="margin-right: 10px">&#xe6f2;</i>
            <i v-else class="iconfont" style="margin-right: 10px">&#xe6f3;</i>
            <span>{{ node.label }}</span>
          </span>
        </div>
      </el-tree>
    </div>
    <el-dialog
      :title="`添加主题到分类《${clickedType.label}》`"
      :visible.sync="showAddTheme"
    >
      <el-form :model="newTheme">
        <el-form-item label="主题名称" label-width="120px">
          <el-input v-model="newTheme.name" autocomplete="off" placeholder="在这里填入新创建的主题名..." />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addNewTheme">确 定</el-button>
        <el-button @click="showAddTheme=false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="`编辑${clickedType.type==='Category'?'主题':'分类'}名称`"
      :visible.sync="showEdit"
    >
      <el-form :model="newTheme">
        <el-form-item label="名称" label-width="120px">
          <el-input v-model="newName" autocomplete="off" placeholder="在这里填入新的名称..." />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="edit">修 改</el-button>
        <el-button @click="showAddTheme=false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deleteCategory, deleteTheme, getAllCategory, updateTheme } from '@/api/category'
const { createNewCategory, createNewCategoryOnly, updateCategory, updateThemeToCategory } = require('@/api/category')
export default {

  data() {
    return {
      newCategoryDate: '',
      showRightMenu: false,
      defaultSrc: 'src/assets/svg/分类.svg',
      filterText: '',
      theme: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      newTheme: {
        name: ''
      },
      clickedType: {},
      showAddTheme: false,
      showEdit: false,
      newName: ''
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree2.filter(val)
    }
  },
  created() {
    this.toRefresh()
  },
  methods: {
    toRefresh() {
      // 获取Theme信息
      this.theme = getAllCategory()
    },
    rightClick(event, data, node, obj) {
      this.showRightMenu = false // 先把模态框关死，目的是：第二次或者第n次右键鼠标的时候 它默认的是true
      this.showRightMenu = true
      this.clickedType = node.data
      const menu = document.querySelector('#menu')
      menu.style.left = event.clientX - 205 + 'px'
      menu.style.top = event.clientY - 57 + 'px'
      // 给整个document添加监听鼠标事件，点击任何位置执行closeRightMenu方法，及时将菜单关闭
      document.addEventListener('click', this.closeRightMenu)
      console.log('event', event, event.clientX, event.clientY)
      console.log('data', data)
      console.log(node)
    },
    nodeClick(data) {
      this.closeRightMenu()
    },
    closeRightMenu() {
      this.showRightMenu = false
      document.removeEventListener('click', this.closeRightMenu)
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.match(value)
    },
    // 结点是否允许被拖拽
    allDrag(moveNode, inNode, type) {
      return moveNode.data.type !== 'Theme'
    },
    // 允许结点是否被放置
    allDrop(moveNode, inNode, type) {
      if (inNode.data.type === 'Theme' && type !== 'next' || (inNode.parent.data.label === moveNode.parent.data.label) || (inNode.data.type === 'Theme' && inNode.data.label === moveNode.parent.data.label)) { return false }
      return true
    },
    dragEnter(draggingNode, dropNode, ev) {
      if (draggingNode.parent === dropNode.parent) {
        return false
      }
      if (dropNode.parent.data !== undefined) {
        dropNode.parent.data.isChoosed = true
      } else {
        dropNode.data.isChoosed = true
      }
      return true
    },
    dragLeave(draggingNode, dropNode, ev) {
      dropNode.parent.data.isChoosed = false
      return true
    },
    handleDrop(draggingNode, dropNode, ev) {
      var dropCategory = dropNode.parent.data.label === undefined ? dropNode.data.label : dropNode.parent.data.label
      this.$confirm('确定要移动主题《' + draggingNode.data.label + '》到分类《' + dropCategory + '》中吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateThemeToCategory(draggingNode.data.label, dropCategory).then(() => {
          this.$message({
            type: 'success',
            message: '移动成功！'
          })
          this.toRefresh()
        })
      })
        .catch(() => {
          this.toRefresh()
        })
    },
    addHandle() {
      this.showAddTheme = true
    },
    editHandle() {
      this.showEdit = true
    },
    // 删除操作
    deleteHandle() {
      var clicked = this.clickedType
      if (clicked.type === 'Category') {
        this.$confirm('确定要删除主题《' + clicked.label + '》吗? 删除后该主题下所有文章主题会被设为空!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteTheme(clicked.label).then((res) => {
            this.$message({
              type: 'success',
              message: '删除主题《' + clicked.label + '》成功!'
            })
            this.toRefresh()
          })
        })
      } else {
        this.$confirm('确定要删除分类《' + clicked.label + '》吗? 删除后该分类下所有主题会被设为《未分类》!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteCategory(clicked.label).then((res) => {
            this.$message({
              type: 'success',
              message: '删除分类《' + clicked.label + '》成功!'
            })
            this.toRefresh()
          })
        })
      }
    },
    // 创建一个新的分类
    addNewCategoryOnly() {
      for (const category of this.theme) {
        if (category.label === this.newCategoryDate) {
          this.$message({
            type: 'warning',
            message: '该分类已经存在！'
          })
          return
        }
        createNewCategoryOnly(this.newCategoryDate).then((res) => {
          this.$message({
            type: 'success',
            message: '创建分类《' + this.newCategoryDate + '》成功!'
          })
          this.toRefresh()
        })
      }
    },
    addNewTheme() {
      if (!this.checkTheme(this.newTheme.name)) { return }
      createNewCategory(this.newTheme.name, this.clickedType.label).then((res) => {
        this.$message({
          type: 'success',
          message: '创建主题《' + this.newTheme.name + '》成功!'
        })
        this.showAddTheme = false
        this.newTheme = {}
        this.toRefresh()
      })
    },
    edit() {
      if (this.clickedType.type === 'Theme') {
        if (!this.checkCategory(this.newName)) { return }
        updateCategory(this.clickedType.label, this.newName).then((res) => {
          this.$message({
            type: 'success',
            message: '编辑分类名称成功!'
          })
          this.showEdit = false
          this.newName = ''
          this.toRefresh()
        })
      } else {
        if (!this.checkTheme(this.newName)) { return }
        updateTheme(this.clickedType.label, this.newName).then((res) => {
          this.$message({
            type: 'success',
            message: '编辑主题名称成功!'
          })
          this.showEdit = false
          this.newName = ''
          this.toRefresh()
        })
      }
    },
    checkTheme(name) {
      console.log('ok')
      for (const category of this.theme) {
        if (category.children === undefined) {
          continue
        }
        for (const theme of category.children) {
          if (name === theme.label) {
            this.$message({
              type: 'warning',
              message: '该主题名称已经在   ' + category.label + '   中存在！'
            })
            return false
          }
        }
      }
      return true
    },
    checkCategory(name) {
      for (const category of this.theme) {
        if (this.newName === category.label) {
          this.$message({
            type: 'warning',
            message: '该分类已存在！'
          })
          return false
        }
      }
      return true
    }
  }
}
</script>

<style>
.app-container-tree .el-tree-node.is-current > .el-tree-node__content {
  background: rgba(22, 119, 255, 0.1);
  border-right: 3px solid #1677ff;
  color: #187aff;
}
.app-container-tree .el-tree-node__expand-icon {
  color: rgb(0, 112, 255);
}
.app-container-tree .is-leaf {
  color: rgba(0, 0, 0, 0);
}
.app-container-tree .dev-type-main-left {
  overflow: auto;
  padding: 10px;
}
.app-container-tree .rights-menu {
  cursor: pointer;
  z-index: 1;
  position: absolute;
  height: 130px;
  width: 100px;
  position: absolute;
  border-radius: 5px;
  border: 1px solid #ccc;
  background-color: white;
}
.menu-item {
//display: block;
  line-height: 20px;
  text-align: left;
  font-size: 14px;
  padding-top: 10px;
  padding-bottom: 10px;
  color: #606266;
}
.menu-item:hover{
  background-color: #F5F7FA;
  color: #409EFF;
}
li:hover {
  background-color: #edf6ff;
  color: #606266;
}
.title-boxs {
   display: grid;
   grid-template-columns: 22fr 2fr;
   margin-left: 10px;
   margin-top: 10px;
  margin-bottom: 10px;
 }

</style>
